package com.gitee.ywj1352.kaishi.数组和排序;

import java.util.*;

/**
 * 给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有满足条件且不重复的三元组。
 * <p>
 * 注意：答案中不可以包含重复的三元组。
 * <p>
 * 给定数组 nums = [-1, 0, 1, 2, -1, -4]，
 * <p>
 * 满足要求的三元组集合为：
 * [
 * [-1, 0, 1],
 * [-1, -1, 2]
 * ]
 *
 * @author wenjie.yang
 * @date 4/21/2020 2:44 PM
 */
public class 三数之和 {

    public static void main(String[] args) {
//        int[] arr = {13,-5,3,3,-1,13,3,1,-9,-4,9,12,6,-9,-6,-12,-8,3,12,14,4,-15,2,-11,4,-12,10,9,-6,-3,-8,14,7,3,2,-8,-7,-10,8,-8,-7,-6,-11,6,-7,-2,9,-8,8,-2,13,-10,-2,0,-14,-13,-4,11,3,-3,-7,3,-4,8,13,13,-15,-9,10,0,-2,-12,1,2,9,1,8,-4,8,-7,9,7,-2,-15,14,0,-13,-13,-12,-2,-1,-11,8,10,12,6,8,4,12,3,11,-12,-2,-3,5,-15,6,-10,-4,-1,-1,-10,13};
//        long timeMillis = System.currentTimeMillis();
//        List<List<Integer>> lists = threeSum(arr);
//        long end = System.currentTimeMillis();
//        System.out.println(end -timeMillis);
//        for (List<Integer> l : lists) {
//            System.out.println(l);
//        }

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        List<Integer> list1 = list.subList(3,4);
        System.out.println(list1);
    }


    public static List<List<Integer>> threeSum(int[] nums) {
        List<Integer> s = new ArrayList<>();
        List<List<Integer>> hub = new ArrayList<>();
        Set<String> hasSet = new HashSet<>();
        boolean[] dp = new boolean[nums.length];
        dfs(nums, s, dp, 0, hub, hasSet);
        return hub;
    }

    public static void dfs(int[] nums, List<Integer> s, boolean[] dp, int sum, List<List<Integer>> hub, Set<String> hasSet) {
        if (s.size() < 3) {
            for (int i = 0; i < nums.length; i++) {
                if (!dp[i]) {
                    s.add(nums[i]);
                    dp[i] = true;
                    sum = sum + nums[i];
                    if (s.size() == 3 && sum == 0) {
                        List<Integer> dest = new ArrayList<>();
                        dest.addAll(s);
                        Collections.sort(dest);
                        if (!hasSet.contains(dest.toString())) {
                            hub.add(dest);
                            hasSet.add(dest.toString());
                        }
                    }
                    dfs(nums, s, dp, sum, hub, hasSet);
                    dp[i] = false;
                    Integer remove = s.remove(s.size() - 1);
                    sum = sum - remove;
                }
            }
        }
    }

}
